package com.sixmac.platform.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.google.common.base.Strings;
import com.sixmac.util.SMS;
import com.sixmac.util.WeChatConfig;
import com.sixmac.core.base.service.BaseService;
import com.sixmac.core.constant.Const;
import com.sixmac.core.constant.ConstCache;
import com.sixmac.core.constant.ConstCacheKey;
import com.sixmac.core.plugins.dao.Blade;
import com.sixmac.core.toolbox.CMap;
import com.sixmac.core.toolbox.ajax.AjaxResult;
import com.sixmac.core.toolbox.cache.CacheKit;
import com.sixmac.core.toolbox.kit.JsonKit;
import com.sixmac.core.toolbox.kit.LogKit;
import com.sixmac.core.toolbox.kit.RandomKit;
import com.sixmac.module.Installer;
import com.sixmac.module.Landlord;
import com.sixmac.platform.service.LoginService;
import com.sixmac.utils.HttpRequestUtil;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;
import java.util.UUID;

/**
 * Created by admin on 2018/8/31.
 */
@Service
public class LoginServiceImpl extends BaseService<Landlord> implements LoginService {


    @Resource(name = "chatConfig")
    WeChatConfig weChatConfig;

    public AjaxResult login(String code, String headImage, String name) {
        AjaxResult res = new AjaxResult();
        //小程序唯一标识   (在微信小程序管理后台获取)
        String wxspAppid = weChatConfig.getAppId();
        // String wxspAppid = "wx0cc3a5d6d43a61e2";
        //小程序的 app secret (在微信小程序管理后台获取)
        String wxspSecret = weChatConfig.getSecret();
        //String wxspSecret = "461b79aacda17f8e0805d713242d7c77";
        //授权（必填）
        String grant_type = "authorization_code";
        //////////////// 1、向微信服务器 使用登录凭证 code 获取 session_key 和 openid ////////////////
        //请求参数
        String params = "appid=" + wxspAppid + "&secret=" + wxspSecret + "&js_code=" + code + "&grant_type=" + grant_type;
        //发送请求
        String sr = HttpRequestUtil.sendGet("https://api.weixin.qq.com/sns/jscode2session", params);
        //解析相应内容（转换成json对象）
        JSONObject json = JsonKit.parse(sr);
        //获取会话密钥（session_key）
        //  String session_key = json.get("session_key").toString();
        //用户的唯一标识（openid）
        String openId = (String) json.get("openid");


        String token = UUID.randomUUID().toString();
        Installer installer  = Blade.create(Installer.class).findFirstBy("wechatKey=#{wechatKey}", getData("wechatKey", openId));

        if (installer != null) {
            installer.setToken(token);
            CacheKit.put(ConstCache.SYS_USER + ConstCacheKey.USER_AUTH_TOKEN, token, installer);
            HashMap<String,Object> data = new HashMap<>();
            data.put("token",token);
            data.put("installer", installer);
            return res.setData(data);
        }

        Landlord landlord = Blade.create(Landlord.class).findFirstBy("wechatKey=#{wechatKey}", getData("wechatKey", openId));

        if (landlord!=null){//用户已存在
            if (landlord.getStatus()!=null&&landlord.getStatus() == 2) {
                return error("用户被冻结");
            }
            landlord.settoken(token);
            CacheKit.put(ConstCache.SYS_USER + ConstCacheKey.USER_AUTH_TOKEN, token, landlord);
            HashMap<String,Object> data = new HashMap<>();
            data.put("token",token);
            data.put("landlord", landlord);
            return res.setData(data);
        }

        CacheKit.put(ConstCache.SYS_USER + ConstCacheKey.USER_AUTH_TOKEN, token, openId);

        res.setCode(0);
        HashMap<String,Object> data = new HashMap<>();
        data.put("status", 0);
        data.put("token",token);

        return res.setData(data);
    }


    private static final String LOGIN = "1";


    public AjaxResult bindMobile(String token, String phone, String captcha) {
        AjaxResult res = new AjaxResult();

        Object object =  CacheKit.get(ConstCache.SYS_USER + ConstCacheKey.USER_AUTH_TOKEN, token);
        String openId = null;
        if (object instanceof Landlord){
             openId = ((Landlord)object).getWechatKey();
        }else if (object instanceof Installer){
            openId = ((Installer)object).getWechatKey();
        }else{
             openId = object.toString();
        }

        if (openId == null){
            return error("用户授权错误，请重新授权。");
        }

        //验证通过
        if (this.verifyCaptcha(captcha, phone, LOGIN)) {
            //清除缓存
            this.clearCaptcha(phone, LOGIN);

            Installer installer = Blade.create(Installer.class).findFirstBy("mobile=#{mobile}",getData("mobile", phone));

            if (installer!=null){
                installer.setWechatKey(openId);
                Blade.create(Installer.class).update(installer);

                HashMap<String,Object> installData = new HashMap<>();
                installData.put("installer",installer);
                installData.put("token",token);
                res.setCode(0);
                res.setData(installData);
                return res;
            }

            Landlord landlord = Blade.create(Landlord.class).findFirstBy("mobile='"+phone+"'", null);
            if(landlord!= null){
               landlord.setWechatKey(openId);
                Blade.create(Landlord.class).update(landlord);
            }else{
                landlord = new Landlord();
                landlord.setWechatKey(openId);
                landlord.setCreateDate(new Date());
                landlord.setMobile(phone);
                Blade.create(Landlord.class).saveRtId(landlord);
            }

            HashMap<String,Object> landlordData = new HashMap<>();
            landlordData.put("landlord",landlord);
            landlordData.put("token",token);
            res.setCode(0);
            res.setData(landlordData);
            return res;
        } else {
            return error("验证码错误");
        }

    }


//    public AjaxResult login(String phone, String captcha) {
//        AjaxResult res = new AjaxResult();
//        //验证通过
//        if (this.verifyCaptcha(captcha, phone, LOGIN)) {
//            //清除缓存
//            this.clearCaptcha(phone, LOGIN);
//            Landlord landlord = this.findFirstBy("mobile=#{mobile}", getData("mobile", phone));
//            if (landlord == null) {
//                landlord = new Landlord();
//                landlord.setMobile(phone);
//                landlord.setStatus(1);//激活状态
//                this.saveAndSetKey(landlord);
//            }
//            if (landlord.getStatus() == 2) {
//                return error("用户被冻结");
//            }
//            //审核信息以后再写
////            if ((landlord.getApprove()) == null) {
////
////            }
//            String token = UUID.randomUUID().toString();
//            CacheKit.put(ConstCache.SYS_USER + ConstCacheKey.USER_AUTH_TOKEN, token, landlord);
//            landlord.settoken(token);
//            return res.setData(getData("landlord", landlord));
//        } else {
//            return error("验证码错误");
//        }
//
//    }


    public boolean checkPhoneOrIdCard(Integer id,String phone, String idCard) {
        Landlord landlord = null;
        if (!Strings.isNullOrEmpty(phone)) {
            landlord = this.findFirstBy("mobile=#{mobile}", getData("mobile", phone));
            if (landlord != null&&landlord.getId()!=id) {
                return false;
            }
        }
        if (!Strings.isNullOrEmpty(idCard)) {
            landlord = this.findFirstBy("idCard=#{idCard}", getData("idCard", idCard));
            if (landlord != null&&landlord.getId().intValue()!=id.intValue()) {
                return false;
            }
        }

        return true;
    }


    @Override
    public AjaxResult sendCaptcha(String token,String phone) {
        // 生成验证码
        String code = RandomKit.randomNumbers(6);
        return this.sendCapcha(LOGIN, code, phone);
    }


    private AjaxResult sendCapcha(String type, String message, String mobile) {
        AjaxResult res = AjaxResult.initAjaxResult();
        String _key = mobile + "_" + type;
        Integer count = CacheKit.get(ConstCache.CAPTCHA_COUNT, _key);
        //Const.CAPTCHA_COUNT 最大限制数量
        if (count == Const.CAPTCHA_COUNT) {
            return res.addError("已超出最大限制条数，请稍后再试");
        }
        if (count == null) {
            count = 0;
        }
        String oldCode = CacheKit.get(ConstCache.CAPTCHA, _key);
        if (oldCode == null || oldCode.equals("")) {
            CacheKit.put(ConstCache.CAPTCHA, _key, message);
            oldCode = message;
        }
        //发送·验证法
        CacheKit.put(ConstCache.CAPTCHA_COUNT, _key, ++count);
        LogKit.error("发送的验证码是:" + oldCode + "条数:" + count);

        SMS.send(mobile,oldCode,"60");

        // SendMsgUtil.sendSms(oldCode, String.valueOf(mobile));
        return res.setData(CMap.init().put("captcha", oldCode));
    }


    private void clearCaptcha(String mobile, String type) {
        CacheKit.remove(ConstCache.CAPTCHA, mobile + "_" + type);
        CacheKit.remove(ConstCache.CAPTCHA_COUNT, mobile + "_" + type);
    }

    private Boolean verifyCaptcha(String oldCaptcha, String mobile, String type) {
        String _key = mobile + "_" + type;
        String captcha = CacheKit.get(ConstCache.CAPTCHA, _key);
        if (captcha == null) {
            return false;
        }
        if (captcha.equals(oldCaptcha)) {
            return true;
        }
        return false;
    }
}
